/****************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.     *
 *                                                              *
 * Copyright (C) 2009, Jun Li All rights reserved.              *
 * More about Jun{                                              *
 * Homepage: http://www.jpxx.org/                               *
 * Email   : lijun@jpxx.org                                     *
 * }                                                            *
 * SOFTWARE ENGINEERING COLLEGE OF SICHUAN UNIVERSITY           *
 *                                                              *
 ****************************************************************/
package org.jpxx.web;

import org.apache.log4j.Logger;
import org.jpxx.web.project.ProjectClasspath;
import org.jpxx.web.project.ProjectJar;
import org.jpxx.web.project.ProjectWar;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppClassLoader;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.resource.FileResource;

/**
 * 
 * 测试服务器初始化。通过该类，自动打包所有子项目，并创建WAR。
 * 
 * @author Jun Li lijun@jpxx.org (http://www.jpxx.org)
 * @version 1.0.0 $ org.jpxx.web.WebInit.java $, $Date: 2009-5-1 $
 * 
 */
public class WebInit {

	private static Logger log = Logger.getLogger(WebInit.class);

	/**
	 * 初始化服务器。
	 * 
	 * @throws Exception
	 */
	public static void init() throws Exception {

		String jars[] = new ProjectJar().getAll();

		Server server = new Server();
		Connector connector = new SelectChannelConnector();
		connector.setPort(Constants.DEFAULT_PORT);

		server.setConnectors(new Connector[] { connector });
		WebAppContext context = new WebAppContext();

		WebAppClassLoader loader = new WebAppClassLoader(context);
		loader.addJars(FileResource.newResource(Constants.CLASSPATH + "lib"));
		loader.addClassPath(new ProjectClasspath().get());
		context.setClassLoader(loader);

		context.setWelcomeFiles(new String[] { "index.htm" });
		context.setContextPath("/");
		context.setResourceBase(Constants.WORKING_PATH);
		server.setHandler(context);

		if (Constants.CREATE_WAR) {
			new ProjectWar(jars).create();
		}

		try {
			server.start();
			server.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
			log.error(e);
			System.exit(-1);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			System.exit(-1);
		}
	}
}
